package com.hx.thread.countdownlaunch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Minghua Chen
 * @date 2020-09-05 22:37
 */
public class RunDemo1 {
    private static final Logger logger = LoggerFactory.getLogger(RunDemo1.class);

    public static void main(String[] args) throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            final int no = i + 1;
            Runnable task = () -> {
                try {
                    Thread.sleep((long) (Math.random() * 10000));
                    logger.info(no + "号同学完成1000m跑步");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 类似于减1
                    countDownLatch.countDown();
                }
            };
            service.submit(task);
        }
        logger.info("比赛开始!");
        // countDownLatch.wait();  会报错 Exception in thread "main" java.lang.IllegalMonitorStateException
        countDownLatch.await();
        logger.info("所有人都跑完了,比赛结束!");
        service.shutdown();
    }
}
